<template>
	<view class="my-container">
		<!-- 用户信息 -->
		<view class="user-info">
			<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<image class="avatar"
					:src="userInfo.avatarUrl || ''"
					mode="aspectFill"></image>
			</button>
			<view class="user-detail">
				<view class="name-gender">
					<text class="nickname">{{ userInfo.nickname || '未知' }}</text>
					<text class="gender">{{ userInfo.gender === 0 ? '男' : userInfo.gender === 1 ? '女' : '未知' }}</text>
				</view>
				<view class="user-meta">
					<text class="phone">{{ formattedPhone }}</text>
					<view class="member-level">
						<image class="member-icon" src="/static/icon/皇冠_crown.svg" mode="aspectFit"></image>
						<text>会员等级: {{ "Lv."+userInfo.memberLevel || 0 }}</text>
					</view>
				</view>
			</view>
			<!-- 按钮垂直排列容器 -->
			<view class="btn-group">
				<view class="edit-info-btn" @tap="navigateTo('/pages/my-info/my-info')">
					<text class="btn-text">完善资料</text>
				</view>
				<view class="my-card-btn" @tap="handleMyCardClick">
					<text class="btn-text">我的卡包</text>
				</view>
			</view>
		</view>

		<!-- 充值卡信息 -->
		<scroll-view class="card-info-container" scroll-y="true" v-if="false">
			<view class="card-info" v-for="(card, index) in memberCards" :key="index" @tap="showRechargeDetail(card)">
				<image class="card-image" :src="card.memberCard.imgUrl" mode="aspectFill"></image>
				<view class="card-content">
					<view class="card-title">{{card.memberCard.cardName}}</view>
					<view class="card-details">
						<view class="detail-item" v-if="card.remainingTimes!==0">
							<text class="label">剩余次数</text>
							<text class="value">{{card.remainingTimes}}</text>
						</view>
						<view class="detail-item" v-if="card.balance!==0">
							<text class="label">余额</text>
							<text class="value">{{card.balance}}</text>
						</view>
						<view class="detail-item">
							<text class="label">购买日期</text>
							<text class="value">{{card.createTime || ''}}</text>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 下滑提示 -->
		<view class="swipe-down-hint" v-if="false">
			<text class="hint-text">下滑查看全部会员卡</text>
			<text class="arrow-down">↓</text>
		</view>

		<!-- 功能菜单网格 -->
		<view class="grid-menu">
			<view class="grid-item" @tap="navigateTo('/pages/my-orders/my-orders')">
				<image class="icon blue-icon" src="/static/icon/订单_order.svg" mode="aspectFit"></image>
				<text class="label">全部订单</text>
			</view>
			<view class="grid-item" @tap="navigateTo('/pages/appointment-list/appointment-list')">
				<image class="icon blue-icon" src="/static/icon/历史记录_history.svg" mode="aspectFit"></image>
				<text class="label">预约记录</text>
			</view>
			<view class="grid-item" @tap="navigateTo('/pages/coupon-list/coupon-list')">
				<image class="icon blue-icon" src="/static/icon/优惠券_coupon.svg" mode="aspectFit"></image>
				<text class="label">优惠券</text>
			</view>
			<view class="grid-item" @tap="navigateTo('/pages/footprint-list/footprint-list')">
				<image class="icon blue-icon" src="/static/icon/按最近浏览量排序_recent-views-sort.svg" mode="aspectFit">
				</image>
				<text class="label">浏览记录</text>
			</view>
			<view class="grid-item" @tap="navigateTo('/pages/technician-collect/technician-collect')">
				<image class="icon blue-icon" src="/static/icon/收藏好友_personal-collection.svg" mode="aspectFit"></image>
				<text class="label">老师收藏</text>
			</view>
			<view class="grid-item" @tap="navigateTo('/pages/address/address')">
				<image class="icon blue-icon" src="/static/icon/连接地址1_connect-address-one.svg" mode="aspectFit"></image>
				<text class="label">我的地址</text>
			</view>
			<view class="grid-item" @tap="navigateTo('/pages/my-comment/my-comment')">
				<image class="icon blue-icon" src="/static/icon/评论_comment.svg" mode="aspectFit"></image>
				<text class="label">我的评价</text>
			</view>
			<view class="grid-item" @tap="navigateTo('/pages/report-list/report-list')">
				<image class="icon blue-icon" src="/static/icon/安全台_security-stall.svg" mode="aspectFit"></image>
				<text class="label">售后列表</text>
			</view>
		</view>
		<view class="bottom-options">
			<view class="option-item" @tap="navigateTo('/pages/report-technician/report-technician')">
				<text>举报技师</text>
			</view>
			<view class="option-item" @tap="navigateTo('/pages/feedback/feedback')">
				<text>意见反馈/联系客服</text>
			</view>
			<view class="option-item" @tap="handleLogout">
				<text>退出登录</text>
			</view>
		</view>
		<view class="recharge-popup" v-if="showRechargePopup">
			<view class="popup-mask" @tap="closeRechargePopup"></view>
			<view class="popup-content">
				<!-- 关闭按钮 -->
				<view class="close-btn" @tap="closeRechargePopup">
					<text class="close-icon">×</text>
				</view>
				<scroll-view class="popup-scroll" scroll-y="true">
					<!-- 卡片基本信息 -->
					<view class="card-section">
						<text class="card-name">{{ selectedCard.memberCard.cardName }}</text>
						<text class="card-no">卡号：{{ selectedCard.memberCard.cardNo }}</text>
						<view class="card-image">
							<image :src="selectedCard.memberCard.imgUrl" mode="aspectFill"></image>
						</view>
						<view class="card-desc">
							<text>会员卡描述：{{ selectedCard.memberCard.description }}</text>
						</view>
					</view>

					<!-- 金额/次数明细 -->
					<view class="amount-section">
						<!-- 卡类型信息 -->
						<view class="type-item">
							<text class="item-label">卡片类型</text>
							<text class="item-value">{{ selectedCard.memberCard.cardType === 1 ? '充值卡' : '次卡' }}</text>
						</view>

						<!-- 根据卡类型显示不同内容 -->
						<template v-if="selectedCard.memberCard.cardType === 1">
							<view class="amount-item">
								<text class="item-label">剩余金额</text>
								<text class="item-value">¥{{ selectedCard.balance }}</text>
							</view>
							<view class="amount-item">
								<text class="item-label">会员卡价格</text>
								<text class="item-value">¥{{ selectedCard.memberCard.price }}</text>
							</view>
						</template>
						<template v-else>
							<view class="amount-item">
								<text class="item-label">剩余次数</text>
								<text class="item-value">{{ selectedCard.remainingTimes }}次</text>
							</view>
							<view class="amount-item">
								<text class="item-label">会员卡价格</text>
								<text class="item-value">¥{{ selectedCard.memberCard.price }}</text>
							</view>
						</template>

						<!-- 有效期信息 -->
						<view class="validity-item">
							<text class="item-label">有效期至</text>
							<text class="item-value">{{ selectedCard.memberCard.expireTime }}</text>
						</view>

						<!-- 客服信息 -->
						<view class="service-item">
							<text class="item-label">客服电话</text>
							<text class="item-value">{{ selectedCard.memberCard.customerService }}</text>
						</view>
					</view>

					<!-- 附赠项目区域 -->
					<view class="gifts-section" v-if="cardGifts.length > 0">
						<view class="section-title">附赠项目</view>
						<view class="gifts-list">
							<view class="gift-item" v-for="(gift, index) in cardGifts" :key="index">
								<view class="gift-info">
									<text class="gift-name">{{ gift.projectName}}</text>
								</view>
								<text class="gift-count">x{{ gift.count || 1 }}</text>
							</view>
						</view>
					</view>
				</scroll-view>

				<!-- 购买按钮 -->
				<view class="recharge-btn" @tap="handlePurchase">
					<text>立即充值</text>
				</view>
			</view>
		</view>

		<!-- 客服弹窗 -->
		<view class="service-popup" v-if="showServicePopup">
			<view class="popup-mask" @tap="closeServicePopup"></view>
			<view class="popup-content">
				<view class="phone-info">{{ servicePhone }}可能是一个电话号码，你可以</view>
				<view class="action-list">
					<view class="action-item" @tap="makePhoneCall">呼叫</view>
					<view class="action-item" @tap="copyPhoneNumber">复制号码</view>
					<view class="action-item" @tap="addToContacts">添加到手机通讯录</view>
					<view class="action-item cancel" @tap="closeServicePopup">取消</view>
				</view>
			</view>
		</view>

		<!-- 项目选择弹窗 -->
		<view class="project-popup" v-if="showProjectPopup">
			<view class="popup-mask" @tap="showProjectPopup = false"></view>
			<view class="popup-content">
				<view class="popup-title">选择附赠项目</view>
				<view class="gift-info">
					<text>充值{{ rechargeInfo.times }}次，赠送{{ rechargeInfo.giftTimes }}次</text>
				</view>
				<view class="project-list">
					<view class="project-item" v-for="project in projects" :key="project.id"
						@tap="selectProject(project)">
						<view class="project-info">
							<text class="project-name">{{ project.projectName }}</text>
							<text class="project-price">¥{{ project.price }}</text>
						</view>
						<text class="gift-times">赠送{{ rechargeInfo.giftTimes }}次</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				userInfo: {
					nickname: '',
					avatarUrl: '',
					gender: 0,
					phone: '',
					memberNo: '',
					memberId: '',
					openId: '',
					birthday: '',
					totalPoints: 0,
					availablePoints: 0,
					totalAmount: 0,
					memberLevel: 0
				},
				memberCards: [], // 会员卡列表
				showRechargePopup: false,
				showServicePopup: false,
				servicePhone: '', // 客服电话，将从后端获取
				currentCard: null, // 当前选中的会员卡
				selectedCard: null, // 选中的充值卡
				isWechatBrowser: false, // 是否在微信浏览器中
				wxReady: false, // 微信JSSDK是否已准备就绪
				isSubmitting: false, // 添加提交状态控制
				cardGifts: [], // 会员卡附赠项目列表
				projects: [], // 项目列表
				selectedProject: null, // 选中的项目
				showProjectPopup: false, // 是否显示项目选择弹窗
				rechargeInfo: null, // 充值信息
				isIOS: false
			}
		},

		computed: {
			// 格式化手机号码显示
			formattedPhone() {
				const phone = this.userInfo.phone
				if (!phone) return '未知'
				return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
			}
		},

		onLoad(options) {
			// iOS 首次进入自动刷新
			// this.isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
			// if (this.isIOS && !sessionStorage.getItem('iosRefreshed_my')) {
			//   sessionStorage.setItem('iosRefreshed_my', 'true');
			//   window.location.reload();
			//   return;
			// }
			this.getUserInfo()
			this.getServicePhone() // 获取客服电话
			this.getProjects() // 获取项目列表

			// 处理支付结果
			if (options && options.paymentResult === 'success') {
				// 从缓存获取支付结果
				try {
					const paymentResult = uni.getStorageSync('paymentResult')
					if (paymentResult && paymentResult.success && paymentResult.sourcePageData) {
						this.handlePaymentSuccess(paymentResult)
						// 清除支付结果缓存
						uni.removeStorageSync('paymentResult')
					}
				} catch (e) {
					console.error('处理支付结果失败:', e)
				}
			}

			// 判断是否在微信浏览器中
			// #ifdef H5
			this.isWechatBrowser = /MicroMessenger/i.test(navigator.userAgent)
			if (this.isWechatBrowser) {
				this.initWxConfig() // 初始化微信JSSDK配置
			}
			// #endif
		},

		onShow() {

			this.getUserInfo()
			this.getMemberCards()
		},

		methods: {
			// 获取客服电话
			getServicePhone() {
				uni.request({
					url: `${uni.$config.baseUrl}/system/config/configKey/CustomerServicePhone`,
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							this.servicePhone = res.data.msg || '' // 如果获取失败，使用默认值
						} else {
							console.error('获取客服电话失败:', res.data)
							this.servicePhone = '18655195062' // 使用默认值
						}
					},
					fail: (err) => {
						console.error('请求客服电话失败:', err)
						this.servicePhone = '18655195062' // 使用默认值
					}
				})
			},

			// 初始化微信JSSDK配置 (仅H5环境微信浏览器中使用)
			initWxConfig() {
				// #ifdef H5
				if (!this.isWechatBrowser) return

				const currentUrl = encodeURIComponent(window.location.href.split('#')[0])

				uni.request({
					url: `${uni.$config.baseUrl}/wx/jsapi/config`,
					method: 'GET',
					data: {
						url: currentUrl
					},
					success: (res) => {
						if (res.data && res.data.code === 200 && res.data.data) {
							const config = res.data.data
							// 注册微信配置
							if (window.wx) {
								window.wx.config({
									debug: false,
									appId: config.appId,
									timestamp: config.timestamp,
									nonceStr: config.nonceStr,
									signature: config.signature,
									jsApiList: [
										'updateAppMessageShareData',
										'updateTimelineShareData',
										'chooseImage',
										'previewImage',
										'uploadImage',
										'downloadImage',
										'getLocalImgData',
										'openLocation',
										'getLocation',
										'closeWindow'
									]
								})

								window.wx.ready(() => {
									console.log('微信JSSDK初始化成功')
									this.wxReady = true
								})

								window.wx.error((err) => {
									console.error('微信JSSDK初始化失败:', err)
								})
							}
						}
					},
					fail: (err) => {
						console.error('获取微信JSSDK配置失败:', err)
					}
				})
				// #endif
			},

			// 获取用户信息
			getUserInfo() {
				// 获取用户信息
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null

				if (userInfoStr) {
					try {
						// 如果是字符串，尝试解析
						if (typeof userInfoStr === 'string') {
							const parsed = JSON.parse(userInfoStr)
							if (parsed.code === 200 && parsed.data) {
								userInfo = parsed.data
							} else {
								userInfo = parsed
							}
						} else {
							userInfo = userInfoStr
						}
						if (userInfo) {
							this.userInfo = {
								...this.userInfo,
								...userInfo
							}
						}
					} catch (e) {}
				}
			},
			navigateTo(url) {
				// 其他环境使用普通导航
				uni.navigateTo({
					url
				})
			},
			contactService() {
				this.showServicePopup = true
			},
			handleLogout() {
				uni.showModal({
					title: '提示',
					content: '确定要退出登录吗？',
					success: (res) => {
						if (res.confirm) {
							uni.removeStorageSync('token')
							uni.removeStorageSync('userInfo')
							uni.removeStorageSync('memberId')
							uni.showToast({
								title: '已退出登录',
								icon: 'success'
							})
							setTimeout(() => {
								// #ifdef H5
								if (this.isWechatBrowser) {
									const baseUrl = window.location.href.split('#')[0].split(
										'/pages/')[0]
									window.location.href = baseUrl + '/pages/login/login'
									return
								}
								// #endif
								uni.reLaunch({
									url: '/pages/login/login',
									fail: (err) => {
										// 如果跳转失败，尝试使用navigateTo
										uni.navigateTo({
											url: '/pages/login/login'
										})
									}
								})
							}, 1000)
						}
					}
				})
			},

			// 处理头像选择
			async onChooseAvatar(e) {
				// #ifdef MP-WEIXIN
				const {
					avatarUrl
				} = e.detail
				if (!avatarUrl) {
					uni.showToast({
						title: '获取头像失败',
						icon: 'none'
					})
					return
				}

				await this.uploadAvatar(avatarUrl)
				// #endif

				// #ifdef H5
				if (this.isWechatBrowser && this.wxReady) {
					// 使用微信JSSDK选择图片
					window.wx.chooseImage({
						count: 1,
						sizeType: ['compressed'],
						sourceType: ['album', 'camera'],
						success: (res) => {
							const localId = res.localIds[0]

							// 获取本地图片数据
							window.wx.getLocalImgData({
								localId: localId,
								success: (res) => {
									const localData = res.localData
									// 处理base64图片数据
									let imageData = localData

									// iOS下的图片localData是base64格式，但Android下可能不是
									if (localData.indexOf('data:image') !== 0) {
										imageData = 'data:image/jpeg;base64,' + localData
									}

									// 转换为Blob进行上传
									this.dataURLtoBlob(imageData, (blob) => {
										this.uploadAvatarFile(blob)
									})
								}
							})
						}
					})
				} else {
					// 非微信环境或JSSDK未初始化，使用普通的文件选择
					uni.chooseImage({
						count: 1,
						success: (res) => {
							const tempFilePath = res.tempFilePaths[0]
							this.uploadAvatar(tempFilePath)
						}
					})
				}
				// #endif

				// #ifdef APP-PLUS || APP-NVUE
				uni.chooseImage({
					count: 1,
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]
						this.uploadAvatar(tempFilePath)
					}
				})
				// #endif
			},

			// Base64转Blob (用于微信H5环境)
			dataURLtoBlob(dataURL, callback) {
				// #ifdef H5
				const arr = dataURL.split(',')
				const mime = arr[0].match(/:(.*?);/)[1]
				const bstr = atob(arr[1])
				let n = bstr.length
				const u8arr = new Uint8Array(n)

				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}

				const blob = new Blob([u8arr], {
					type: mime
				})
				callback(blob)
				// #endif
			},

			// 上传头像文件(Blob格式，用于微信H5环境)
			async uploadAvatarFile(blob) {
				// #ifdef H5
				uni.showLoading({
					title: '上传中...'
				})

				try {
					// 获取用户ID
					const memberId = this.userInfo.memberId
					if (!memberId) {
						throw new Error('用户信息异常，请重新登录')
					}

					// 创建FormData对象
					const formData = new FormData()
					formData.append('file', blob, 'avatar.jpg')
					formData.append('id', memberId)

					// 使用原生fetch或XMLHttpRequest上传
					const response = await fetch(`${uni.$config.baseUrl}/member/member/uploadAvatar`, {
						method: 'POST',
						body: formData
					})

					const result = await response.json()

					if (result.code === 200) {
						// 更新本地用户信息
						this.userInfo.avatarUrl = result.data.avatarUrl
						uni.setStorageSync('userInfo', JSON.stringify(this.userInfo))

						uni.showToast({
							title: '更新成功',
							icon: 'success'
						})
					} else {
						throw new Error(result.msg || '上传失败')
					}
				} catch (err) {
					uni.showToast({
						title: err.message || '上传失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
				// #endif
			},

			// 上传头像(通用方法)
			async uploadAvatar(avatarUrl) {
				uni.showLoading({
					title: '上传中...'
				})

				try {
					// 获取用户ID
					const memberId = this.userInfo.memberId
					if (!memberId) {
						throw new Error('用户信息异常，请重新登录')
					}

					const res = await uni.uploadFile({
						url: `${uni.$config.baseUrl}/member/member/uploadAvatar`,
						filePath: avatarUrl,
						name: 'file',
						formData: {
							id: memberId
						},
						header: {
							'content-type': 'multipart/form-data'
						}
					})

					const data = JSON.parse(res.data)
					if (data.code === 200) {
						// 更新本地用户信息
						this.userInfo.avatarUrl = data.data.avatarUrl
						uni.setStorageSync('userInfo', JSON.stringify(this.userInfo))

						uni.showToast({
							title: '更新成功',
							icon: 'success'
						})
					} else {
						throw new Error(data.msg || '上传失败')
					}
				} catch (err) {
					uni.showToast({
						title: err.message || '上传失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},

			// 获取会员卡列表
			getMemberCards() {
				if (!this.userInfo.memberId) return

				uni.showLoading({
					title: '加载中...'
				})

				// 创建请求头
				const header = {}
				const token = uni.getStorageSync('token')
				if (token) {
					header['Authorization'] = 'Bearer ' + token
				}

				uni.request({
					url: `${uni.$config.baseUrl}/usercard/usercard/listByUid`,
					method: 'GET',
					data: {
						memberId: this.userInfo.memberId
					},
					header: header,
					success: (res) => {
						if (res.data.code === 200) {
							this.memberCards = res.data.rows || []
						} else {
							uni.showToast({
								title: res.data.msg || '获取会员卡信息失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('获取会员卡信息失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			},

			// 显示充值卡详情
			showRechargeDetail(card) {
				this.selectedCard = card
				this.showRechargePopup = true
				// 获取会员卡附赠项目
				this.getCardGifts(card.memberCard.id)
			},

			// 获取会员卡附赠项目
			getCardGifts(cardId) {
				if (!cardId) return

				uni.request({
					url: `${uni.$config.baseUrl}/cardgift/cardgift/listAll`,
					method: 'GET',
					data: {
						cardId: cardId
					},
					success: (res) => {
						if (res.data.code === 200) {
							this.cardGifts = res.data.rows || []
						} else {
							console.error('获取会员卡附赠项目失败:', res.data)
						}
					},
					fail: (err) => {
						console.error('请求会员卡附赠项目失败:', err)
					}
				})
			},

			// 获取项目列表
			getProjects() {
				uni.request({
					url: `${uni.$config.baseUrl}/project/project/listAll`,
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							// 过滤出艾灸、刮痧、拔罐项目
							this.projects = res.data.rows.filter(project => ['艾灸', '刮痧', '拔罐'].includes(project
								.projectName))
						}
					},
					fail: (err) => {
						console.error('获取项目列表失败:', err)
					}
				})
			},

			// 处理充值
			handlePurchase() {
				if (!this.selectedCard) return

				// 根据卡类型显示不同的充值选项
				if (this.selectedCard.memberCard.cardType === 1) {
					// 充值卡显示金额选项
					uni.showActionSheet({
						itemList: ['充值1580元', '充值2980元', '充值4980元'],
						success: (res) => {
							const amounts = [1580, 2980, 4980]
							const selectedAmount = amounts[res.tapIndex]

							// 显示项目选择弹窗
							this.showProjectPopup = true

							// 存储充值信息到本地
							this.rechargeInfo = {
								cardId: this.selectedCard.id,
								amount: selectedAmount,
								times: 1,
								giftTimes: 3
							}
							uni.setStorageSync('rechargeInfo', this.rechargeInfo)
						}
					})
				} else {
					// 次卡显示次数选项
					const singlePrice = this.selectedCard.memberCard.oncePrice
					const fiveTimesPrice = singlePrice * 5
					const tenTimesPrice = singlePrice * 10

					uni.showActionSheet({
						itemList: [`充值5次(￥${fiveTimesPrice.toFixed(2)})附赠三次（艾灸/刮痧/拔罐三选一）`,
							`充值10次(￥${tenTimesPrice.toFixed(2)})附赠十次（艾灸/刮痧/拔罐三选一）`
						],
						success: (res) => {
							const times = [5, 10]
							const selectedTimes = times[res.tapIndex]
							const selectedAmount = selectedTimes === 5 ? fiveTimesPrice : tenTimesPrice

							// 显示项目选择弹窗
							this.showProjectPopup = true

							// 存储充值信息到本地
							this.rechargeInfo = {
								cardId: this.selectedCard.id,
								amount: selectedAmount,
								times: selectedTimes,
								giftTimes: selectedTimes === 5 ? 3 : 10
							}
							uni.setStorageSync('rechargeInfo', this.rechargeInfo)
						}
					})
				}
			},

			// 选择项目
			selectProject(project) {
				this.selectedProject = project
				this.showProjectPopup = false

				// 获取存储的充值信息
				const rechargeInfo = uni.getStorageSync('rechargeInfo')
				if (rechargeInfo) {
					// 显示确认弹窗
					uni.showModal({
						title: '充值确认',
						content: `确定要充值${rechargeInfo.times}次吗？\n金额：￥${rechargeInfo.amount.toFixed(2)}\n附赠项目：${project.projectName} ${rechargeInfo.giftTimes}次`,
						success: (modalRes) => {
							if (modalRes.confirm) {
								// 添加项目信息到充值信息
								rechargeInfo.projectId = project.id
								rechargeInfo.projectName = project.projectName
								uni.setStorageSync('rechargeInfo', rechargeInfo)

								this.navigateToPayment(rechargeInfo.amount, rechargeInfo.times)
							}
						}
					})
				}
			},

			// 跳转到支付页面
			navigateToPayment(amount, times = null) {
				// 获取充值信息
				const rechargeInfo = uni.getStorageSync('rechargeInfo')

				// 构建支付参数
				const paymentParams = {
					amount: amount,
					orderType: 2, // 2-会员卡充值
					orderDesc: times ?
						`会员卡充值 ${times}次` : `会员卡充值 ${amount}元`,
					callbackUrl: '/pages/my/my', // 支付完成后的回调页面
					paymentParams: {
						memberId: this.userInfo.memberId,
						cardId: this.selectedCard.id,
						amount: amount,
						times: times,
						paymentMethod: 1, // 1-微信支付
						orderType: 2, // 2-会员卡充值
						orderSource: 1 // 1-H5
					},
					sourcePageData: {
						cardId: this.selectedCard.id,
						amount: amount,
						times: times,
						projectId: rechargeInfo.projectId,
						projectName: rechargeInfo.projectName,
						giftTimes: rechargeInfo.giftTimes
					}
				}

				// 使用缓存存储支付参数
				uni.setStorageSync('paymentData', paymentParams)

				// 跳转到支付页面
				uni.navigateTo({
					url: `/pages/pay-public/pay-public?login=false`
				})
			},

			// 处理支付成功
			handlePaymentSuccess(paymentResult) {
				if (paymentResult.sourcePageData) {
					// 支付成功，更新会员卡余额或次数
					this.updateCardBalance(
						this.userInfo.memberId,
						paymentResult.sourcePageData.cardId,
						paymentResult.sourcePageData.amount,
						paymentResult.sourcePageData.times
					)
				}
			},

			// 更新会员卡余额或次数
			updateCardBalance(memberId, cardId, amount, times = null) {
				// 显示加载中
				uni.showLoading({
					title: '处理中...'
				})

				// 构建充值数据
				const rechargeData = {
					memberId: memberId,
					cardId: cardId,
					amount: amount,
					times: times, // 添加次数参数
					type: 1 // 1-充值
				}

				// 调用充值接口
				uni.request({
					url: `${uni.$config.baseUrl}/usercard/usercard/recharge`,
					method: 'POST',
					data: rechargeData,
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							uni.showToast({
								title: '充值成功',
								icon: 'success',
								duration: 2000,
								success: () => {
									// 刷新会员卡信息
									this.getMemberCards()
									// 关闭充值弹窗
									this.closeRechargePopup()
								}
							})
						} else {
							uni.showToast({
								title: res.data.msg || '充值失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('充值失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					},
					complete: () => {
						uni.hideLoading()
						this.isSubmitting = false
					}
				})
			},

			// 关闭充值卡详情
			closeRechargePopup() {
				this.showRechargePopup = false
			},

			// 拨打电话
			makePhoneCall() {
				// #ifdef H5
				if (this.isWechatBrowser) {
					// 在微信H5环境中，直接使用a标签拨打电话
					window.location.href = `tel:${this.servicePhone}`
					this.showServicePopup = false
					return
				}
				// #endif

				uni.makePhoneCall({
					phoneNumber: this.servicePhone,
					success: () => {
						this.showServicePopup = false
					},
					fail: (err) => {
						// 用户取消拨打电话时不显示错误提示
						if (err.errMsg && err.errMsg.indexOf('cancel') !== -1) {
							return
						}
						console.error('拨打电话失败:', err)
						uni.showToast({
							title: '拨打电话失败',
							icon: 'none'
						})
					}
				})
			},

			// 复制电话号码
			copyPhoneNumber() {
				// #ifdef H5
				if (this.isWechatBrowser) {
					// 在H5环境中创建一个临时的textarea元素来复制内容
					const textarea = document.createElement('textarea')
					textarea.value = this.servicePhone
					textarea.style.position = 'fixed'
					textarea.style.top = '0'
					textarea.style.left = '0'
					textarea.style.width = '2em'
					textarea.style.height = '2em'
					textarea.style.padding = '0'
					textarea.style.border = 'none'
					textarea.style.outline = 'none'
					textarea.style.boxShadow = 'none'
					textarea.style.background = 'transparent'
					document.body.appendChild(textarea)
					textarea.focus()
					textarea.select()

					try {
						document.execCommand('copy')
						uni.showToast({
							title: '已复制号码',
							icon: 'success'
						})
					} catch (err) {
						uni.showToast({
							title: '复制失败',
							icon: 'none'
						})
					}

					document.body.removeChild(textarea)
					return
				}
				// #endif

				uni.setClipboardData({
					data: this.servicePhone,
					success: () => {
						uni.showToast({
							title: '已复制号码',
							icon: 'success'
						})
					}
				})
			},

			// 添加到通讯录
			addToContacts() {
				// #ifdef H5
				if (this.isWechatBrowser) {
					// 在微信H5环境中，通过创建vcard格式的链接添加联系人
					const vcard = `BEGIN:VCARD
VERSION:3.0
FN:客服
TEL:${this.servicePhone}
END:VCARD`

					const blob = new Blob([vcard], {
						type: 'text/vcard'
					})
					const url = URL.createObjectURL(blob)

					const a = document.createElement('a')
					a.href = url
					a.download = '客服.vcf'
					a.click()

					URL.revokeObjectURL(url)

					uni.showToast({
						title: '请保存下载的文件',
						icon: 'none',
						duration: 2000
					})

					// 部分提示
					setTimeout(() => {
						uni.showModal({
							title: '添加联系人',
							content: '在微信环境中无法直接添加联系人。已下载vCard文件，您可以手动将其导入到通讯录。',
							showCancel: false
						})
					}, 1000)

					this.showServicePopup = false
					return
				}
				// #endif

				uni.addPhoneContact({
					firstName: '客服',
					mobilePhoneNumber: this.servicePhone,
					success: () => {
						uni.showToast({
							title: '已添加到通讯录',
							icon: 'success'
						})
						this.showServicePopup = false
					},
					fail: () => {
						uni.showToast({
							title: '添加失败',
							icon: 'none'
						})
					}
				})
			},

			// 关闭客服弹窗
			closeServicePopup() {
				this.showServicePopup = false
			},

			handleMyCardClick() {
				uni.navigateTo({
					url: '/pages/my-card/my-card'
				})
			},
		}
	}
</script>

<style lang="scss">
	.my-container {
		min-height: 60vh;
		background: #F8F8F8;
		padding: 24rpx;

		.user-info {
			background: #FFFFFF;
			padding: 36rpx;
			border-radius: 16rpx;
			display: flex;
			align-items: center;
			margin-bottom: 24rpx;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);

			.avatar-wrapper {
				position: relative;
				margin-right: 24rpx;
				padding: 0;
				width: 120rpx;
				height: 120rpx;
				background: none;
				border: none;

				&::after {
					border: none;
				}

				.avatar {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					border: 2rpx solid #f0f0f0;
					box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
				}

				&:active {
					opacity: 0.8;
				}
			}

			.user-detail {
				flex: 1;

				.name-gender {
					display: flex;
					align-items: center;
					margin-bottom: 12rpx;

					.nickname {
						font-size: 36rpx;
						color: #333333;
						font-weight: 600;
						margin-right: 14rpx;
					}

					.gender {
						font-size: 28rpx;
						color: #666666;
						background: #F5F5F5;
						padding: 4rpx 16rpx;
						border-radius: 20rpx;
					}
				}

				.user-meta {
					display: flex;
					flex-direction: column;
					gap: 8rpx;

					.phone {
						font-size: 30rpx;
						color: #999999;
					}

					.member-level {
						font-size: 28rpx;
						color: #2B87FF;
						background: rgba(43, 135, 255, 0.1);
						padding: 4rpx 16rpx;
						border-radius: 20rpx;
						align-self: flex-start;
						display: flex;
						align-items: center;
						gap: 8rpx;

						.member-icon {
							width: 28rpx;
							height: 28rpx;
						}
					}
				}
			}

			.btn-group {
				display: flex;
				flex-direction: column;
				align-items: flex-start;
				margin-left: 20rpx;
			}

			.edit-info-btn,
			.my-card-btn {
				background: #2B87FF;
				color: #fff;
				border-radius: 30rpx;
				padding: 0 32rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				font-weight: bold;
				white-space: nowrap;
				width: 200rpx;
			}

			.edit-info-btn {
				margin-top: 0;
			}

			.my-card-btn {
				margin-top: 16rpx;
			}

			.btn-text {
				white-space: nowrap;
				font-size: 28rpx;
			}
		}

		.card-info-container {
			height: 320rpx;
			padding: 20rpx;

			.card-info {
				position: relative;
				border-radius: 16rpx;
				padding: 24rpx;
				margin-bottom: 24rpx;
				box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
				display: flex;
				align-items: center;
				background: #FFFFFF;
				transition: all 0.3s;

				&:active {
					transform: scale(0.98);
					box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.08);
				}

				.card-image {
					width: 200rpx;
					height: 200rpx;
					border-radius: 12rpx;
					margin-right: 24rpx;
					flex-shrink: 0;
					box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
				}

				.card-content {
					flex: 1;
					min-width: 0;

					.card-title {
						font-size: 36rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 24rpx;
					}

					.card-details {
						.detail-item {
							display: flex;
							flex-direction: column;
							margin-bottom: 18rpx;

							&:last-child {
								margin-bottom: 0;
							}

							.label {
								font-size: 30rpx;
								color: #666;
								margin-bottom: 8rpx;
							}

							.value {
								font-size: 32rpx;
								color: #011228;
								font-weight: 600;
							}
						}
					}
				}
			}
		}

		.swipe-down-hint {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 20rpx 0;
			margin: 10rpx 0;

			.hint-text {
				font-size: 28rpx;
				color: #999;
				margin-bottom: 8rpx;
			}

			.arrow-down {
				font-size: 36rpx;
				color: #2B87FF;
				animation: bounce 2s infinite;
			}
		}

		@keyframes bounce {

			0%,
			20%,
			50%,
			80%,
			100% {
				transform: translateY(0);
			}

			40% {
				transform: translateY(-10rpx);
			}

			60% {
				transform: translateY(-5rpx);
			}
		}

		.grid-menu {
			background: #FFFFFF;
			border-radius: 16rpx;
			padding: 24rpx;
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			gap: 24rpx;
			margin-bottom: 24rpx;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

			.grid-item {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 16rpx 0;
				transition: all 0.3s;

				.icon {
					width: 56rpx;
					height: 56rpx;
					margin-bottom: 16rpx;
				}

				// For Safari and other browsers that support CSS filter
				.blue-icon {
					filter: brightness(0) saturate(100%) invert(44%) sepia(93%) saturate(1642%) hue-rotate(194deg) brightness(102%) contrast(96%) drop-shadow(0 2rpx 4rpx rgba(43, 135, 255, 0.2));
				}

				.label {
					font-size: 28rpx;
					color: #333333;
				}

				&:active {
					opacity: 0.7;
					transform: scale(0.95);
				}
			}
		}

		.bottom-options {
			background: #FFFFFF;
			border-radius: 16rpx;
			overflow: hidden;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

			.option-item {
				padding: 36rpx;
				text-align: center;
				font-size: 32rpx;
				color: #333333;
				border-bottom: 1rpx solid #EEEEEE;
				transition: all 0.2s;

				&:last-child {
					border-bottom: none;
				}

				&:active {
					background: #F5F5F5;
				}
			}
		}

		.recharge-popup {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 999;

			.popup-mask {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background: rgba(0, 0, 0, 0.6);
				backdrop-filter: blur(4px);
			}

			.popup-content {
				position: absolute;
				left: 30rpx;
				right: 30rpx;
				top: 50%;
				transform: translateY(-50%);
				background: #FFFFFF;
				border-radius: 24rpx;
				padding: 40rpx;
				box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
				max-height: 80vh;
				display: flex;
				flex-direction: column;

				.popup-scroll {
					flex: 1;
					overflow-y: auto;
					padding-right: 10rpx;

					&::-webkit-scrollbar {
						width: 6rpx;
					}

					&::-webkit-scrollbar-thumb {
						background: rgba(0, 0, 0, 0.1);
						border-radius: 3rpx;
					}

					&::-webkit-scrollbar-track {
						background: transparent;
					}
				}

				.close-btn {
					position: absolute;
					top: 20rpx;
					right: 20rpx;
					width: 60rpx;
					height: 60rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					z-index: 10;

					.close-icon {
						font-size: 50rpx;
						color: #999;
						line-height: 1;
					}

					&:active {
						opacity: 0.7;
					}
				}

				.card-section {
					margin-bottom: 30rpx;
					text-align: center;

					.card-name {
						font-size: 44rpx;
						font-weight: bold;
						margin-bottom: 16rpx;
						color: #333333;
						position: relative;
						display: inline-block;

						&::after {
							content: '';
							position: absolute;
							bottom: -8rpx;
							left: 50%;
							transform: translateX(-50%);
							width: 60rpx;
							height: 6rpx;
							background: #2B87FF;
							border-radius: 3rpx;
						}
					}

					.card-no {
						font-size: 30rpx;
						color: #999999;
						margin-bottom: 30rpx;
					}

					.card-image {
						width: 100%;
						height: 240rpx;
						border-radius: 16rpx;
						margin-bottom: 30rpx;
						overflow: hidden;
						box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.08);

						image {
							width: 100%;
							height: 100%;
							object-fit: cover;
						}
					}

					.card-desc {
						font-size: 32rpx;
						color: #666666;
						line-height: 1.6;
						padding: 24rpx;
						background: #F8F9FA;
						border-radius: 12rpx;
						margin-bottom: 20rpx;
					}
				}

				.amount-section {
					background: #F8F9FA;
					border-radius: 16rpx;
					padding: 30rpx;

					.type-item,
					.validity-item,
					.service-item {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 20rpx 0;
						border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);

						.item-label {
							font-size: 32rpx;
							color: #666666;
						}

						.item-value {
							font-size: 32rpx;
							color: #333333;
							font-weight: 500;
						}
					}

					.amount-item {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 20rpx 0;
						border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);

						.item-label {
							font-size: 32rpx;
							color: #666666;
						}

						.item-value {
							font-size: 36rpx;
							color: #2B87FF;
							font-weight: 600;
						}
					}

					.validity-item,
					.service-item {
						border-bottom: none;
					}
				}

				.gifts-section {
					background: #F8F9FA;
					border-radius: 16rpx;
					padding: 30rpx;
					margin-top: 20rpx;

					.section-title {
						font-size: 34rpx;
						font-weight: 600;
						color: #333;
						margin-bottom: 20rpx;
						position: relative;
						padding-left: 20rpx;

						&::before {
							content: '';
							position: absolute;
							left: 0;
							top: 50%;
							transform: translateY(-50%);
							width: 6rpx;
							height: 24rpx;
							background: #2B87FF;
							border-radius: 3rpx;
						}
					}

					.gifts-list {
						.gift-item {
							display: flex;
							justify-content: space-between;
							align-items: center;
							padding: 16rpx 0;
							border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);

							&:last-child {
								border-bottom: none;
							}

							.gift-info {
								flex: 1;

								.gift-name {
									font-size: 32rpx;
									color: #333;
									font-weight: 500;
									margin-bottom: 8rpx;
									display: block;
								}

								.gift-desc {
									font-size: 28rpx;
									color: #999;
									display: block;
								}
							}

							.gift-count {
								font-size: 32rpx;
								color: #2B87FF;
								font-weight: 500;
								margin-left: 20rpx;
							}
						}
					}
				}

				.recharge-btn,
				.disabled-btn {
					width: 100%;
					height: 90rpx;
					border-radius: 45rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-top: 40rpx;
					transition: all 0.3s;

					text {
						font-size: 36rpx;
						font-weight: 600;
					}
				}

				.recharge-btn {
					background: linear-gradient(135deg, #42A5F5, #1976D2);
					box-shadow: 0 6rpx 16rpx rgba(43, 135, 255, 0.3);

					text {
						color: #FFFFFF;
					}

					&:active {
						transform: translateY(2rpx);
						box-shadow: 0 4rpx 8rpx rgba(43, 135, 255, 0.2);
					}
				}

				.disabled-btn {
					background: #CCCCCC;

					text {
						color: #FFFFFF;
					}
				}
			}
		}

		.service-popup {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 999;

			.popup-mask {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background: rgba(0, 0, 0, 0.6);
			}

			.popup-content {
				position: fixed;
				left: 0;
				right: 0;
				bottom: 0;
				background: #F8F8F8;
				border-radius: 24rpx 24rpx 0 0;
				overflow: hidden;
				box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);

				.phone-info {
					padding: 44rpx;
					text-align: center;
					font-size: 36rpx;
					color: #333;
					background: #FFFFFF;
				}

				.action-list {
					.action-item {
						height: 120rpx;
						line-height: 120rpx;
						text-align: center;
						font-size: 36rpx;
						color: #2B87FF;
						background: #FFFFFF;
						border-top: 1rpx solid #EEEEEE;

						&:active {
							background: #F5F5F5;
						}

						&.cancel {
							color: #333;
							margin-top: 20rpx;
							font-weight: 500;
						}
					}
				}
			}
		}

		.project-popup {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 999;

			.popup-mask {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background: rgba(0, 0, 0, 0.6);
			}

			.popup-content {
				position: absolute;
				left: 30rpx;
				right: 30rpx;
				top: 50%;
				transform: translateY(-50%);
				background: #FFFFFF;
				border-radius: 24rpx;
				padding: 40rpx;
				box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);

				.popup-title {
					font-size: 36rpx;
					font-weight: bold;
					text-align: center;
					margin-bottom: 30rpx;
				}

				.gift-info {
					text-align: center;
					font-size: 32rpx;
					color: #2B87FF;
					margin-bottom: 30rpx;
					padding: 12rpx 0;
					background: rgba(43, 135, 255, 0.1);
					border-radius: 8rpx;
				}

				.project-list {
					.project-item {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 24rpx;
						border-bottom: 1rpx solid #EEEEEE;
						transition: all 0.2s;

						&:last-child {
							border-bottom: none;
						}

						.project-info {
							flex: 1;

							.project-name {
								font-size: 32rpx;
								color: #333333;
								margin-bottom: 8rpx;
								display: block;
								font-weight: 500;
							}

							.project-price {
								font-size: 28rpx;
								color: #2B87FF;
							}
						}

						.gift-times {
							font-size: 28rpx;
							color: #2B87FF;
							background: rgba(43, 135, 255, 0.1);
							padding: 8rpx 20rpx;
							border-radius: 20rpx;
						}

						&:active {
							background: #F5F5F5;
							transform: scale(0.98);
						}
					}
				}
			}
		}
	}
</style>